#!/usr/bin/env python

from PIL import Image
import sys

def print_str( img ):
    img_str = img.tostring()
    # print img_str
    x = img.size[0]
    y = img.size[1]
    #print '%i %i'%(x, y)
    #for i in range(1, img.size[1]):
    #    for j in range(1, img.size[0]):
    #        # print '%d'%(img[x-1+(y-1)*(x-1)])
    #        print img_str[j-1+(i-1)*(j-1)].encode('hex_codec')
    #    print '\n'
    counter = 0
    for i in img_str:
        # sys.stdout.write(i[0].encode('hex_codec'))
        sys.stdout.write('%02x'%((~int(i[0].encode('hex_codec'), 16)&0xFF)))
        # sys.stdout.write('\n')
        counter += 8
        if counter >=  x:
            sys.stdout.write('\n')
            counter = 0
    sys.stdout.write('\n')

im = Image.open("test.png")

print im.size
x = im.size[0]
y = im.size[1]
if y > 48*8:
    y = 48*8
    x = int(im.size[0] * y/im.size[1])
    # im = im.transform((x, y), Image.EXTENT, (0,0,im.size[0],im.size[1]))
    # print im.size

if y%8 > 0:
    y = (y/8+1)*8
if x%8 > 0:
    x = (x/8+1)*8
    
im = im.transform((x, y), Image.EXTENT, (0,0,im.size[0],im.size[1]))
print im.size
# bw = im.convert("1")
# print bw.tobitmap()
# print_str(bw)

im = im.transpose(Image.ROTATE_270)
im = im.transpose(Image.FLIP_LEFT_RIGHT)
print im.size

bw = im.convert("1")
print_str(bw)

# out = bw.rotate(270, Image.NEAREST, 1)

# im.transpose(method)
# Method can be one of the following: FLIP_LEFT_RIGHT, FLIP_TOP_BOTTOM, ROTATE_90, ROTATE_180, or ROTATE_270.

# print out.tostring()